<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 实验室辅助管理系统</title>
    <link rel="stylesheet" th:href="@{/css/style.css}">
    <link rel="stylesheet" th:href="@{/css/fontawesome-local.css}">
    <style>
        /* 禁用按钮样式 */
        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            pointer-events: none;
        }
        
        .btn:disabled:hover {
            transform: none;
            box-shadow: none;
        }
        
        /* 当前用户标识 */
        .current-user-badge {
            background: linear-gradient(135deg, #17a2b8, #138496);
            color: white;
            font-size: 11px;
            padding: 2px 6px;
            border-radius: 3px;
            margin-left: 5px;
            display: inline-block;
        }
        
        /* 表格行高亮当前用户 */
        tr.current-user {
            background-color: rgba(23, 162, 184, 0.1);
        }
        
        tr.current-user:hover {
            background-color: rgba(23, 162, 184, 0.15);
        }
    </style>
</head>
<body>
    <div class="management-container">
        <!-- 侧边栏 -->
        <nav class="sidebar">
            <div class="sidebar-header">
                <h2><i class="fas fa-users"></i> 用户管理</h2>
            </div>
            <ul class="nav-menu">
                <li><a th:href="@{/dashboard}"><i class="fas fa-tachometer-alt"></i> 系统仪表盘</a></li>
                <li><a th:href="@{/college-management}"><i class="fas fa-university"></i> 学院管理</a></li>
                <li><a th:href="@{/term-management}"><i class="fas fa-calendar-alt"></i> 学期管理</a></li>
                <li><a th:href="@{/laboratory-management}"><i class="fas fa-microscope"></i> 实验室管理</a></li>
                <li class="active"><a th:href="@{/user-management}"><i class="fas fa-users"></i> 用户管理</a></li>
                <li><a th:href="@{/assignment-management}"><i class="fas fa-user-cog"></i> 管理员分配</a></li>
            </ul>
        </nav>

        <!-- 主内容区 -->
        <main class="main-content">
            <!-- 顶部栏 -->
            <header class="top-bar">
                <div class="top-bar-left">
                    <h1>用户管理</h1>
                </div>
                <div class="top-bar-right">
                    <div class="user-info">
                        <span th:text="${currentUser.name}">管理员</span>
                        <a th:href="@{/logout}" class="logout-btn">退出</a>
                    </div>
                </div>
            </header>

            <!-- 内容区域 -->
            <div class="content">
                <!-- 操作栏 -->
                <div class="action-bar">
                    <button class="btn btn-primary" onclick="showAddUserModal()">
                        <i class="fas fa-plus"></i> 添加用户
                    </button>
                    <div class="search-box">
                        <input type="text" id="searchInput" placeholder="搜索用户名或姓名..." onkeyup="filterUsers()">
                        <i class="fas fa-search"></i>
                    </div>
                </div>

                <!-- 用户列表 -->
                <div class="card">
                    <div class="card-header">
                        <h3>用户列表</h3>
                        <span class="badge" th:text="${users.size()} + ' 个用户'">0 个用户</span>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table" id="userTable">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>用户名</th>
                                        <th>姓名</th>
                                        <th>角色</th>
                                        <th>所属学院</th>
                                        <th>联系方式</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr th:each="user : ${users}" th:class="${user.id == currentUser.id ? 'current-user' : ''}">
                                        <td th:text="${user.id}">1</td>
                                        <td th:text="${user.username}">admin</td>
                                        <td th:text="${user.name}">管理员</td>
                                        <td>
                                            <span th:if="${user.role.name() == 'ADMIN'}" class="badge badge-success">超级管理员</span>
                                            <span th:if="${user.role.name() == 'LAB_MANAGER'}" class="badge badge-info">实验室管理员</span>
                                        </td>
                                        <td th:text="${user.college != null ? user.college.name : '无'}">计算机科学与技术学院</td>
                                        <td th:text="${user.contactInfo != null ? user.contactInfo : '无'}">admin@university.edu</td>
                                        <td>
                                            <span class="badge badge-success">活跃</span>
                                            <span th:if="${user.id == currentUser.id}" 
                                                  class="current-user-badge">
                                                <i class="fas fa-user"></i> 当前用户
                                            </span>
                                        </td>
                                        <td>
                                            <button class="btn btn-sm btn-info" 
                                                    th:data-id="${user.id}" onclick="editUserFromButton(this)"
                                                    th:disabled="${user.id == currentUser.id}"
                                                    th:title="${user.id == currentUser.id ? '不能编辑自己的信息' : ''}">
                                                <i class="fas fa-edit"></i> 编辑
                                            </button>
                                            <button class="btn btn-sm btn-warning" 
                                                    th:data-id="${user.id}" onclick="resetPasswordFromButton(this)"
                                                    th:disabled="${user.id == currentUser.id}"
                                                    th:title="${user.id == currentUser.id ? '不能重置自己的密码' : ''}">
                                                <i class="fas fa-key"></i> 重置密码
                                            </button>
                                            <button class="btn btn-sm btn-danger" 
                                                    th:data-id="${user.id}" onclick="deleteUserFromButton(this)"
                                                    th:if="${user.role.name() != 'ADMIN' and user.id != currentUser.id}"
                                                    th:title="删除用户">
                                                <i class="fas fa-trash"></i> 删除
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- 添加用户模态框 -->
    <div id="addUserModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>添加用户</h3>
                <span class="close" onclick="closeModal('addUserModal')">&times;</span>
            </div>
            <div class="modal-body">
                <form id="addUserForm">
                    <div class="form-group">
                        <label for="username">用户名</label>
                        <input type="text" id="username" name="username" class="form-control" placeholder="请输入用户名" required>
                    </div>
                    <div class="form-group">
                        <label for="name">姓名</label>
                        <input type="text" id="name" name="name" class="form-control" placeholder="请输入姓名" required>
                    </div>
                    <div class="form-group">
                        <label for="password">密码</label>
                        <input type="password" id="password" name="password" class="form-control" placeholder="请输入密码" required>
                    </div>
                    <div class="form-group">
                        <label for="role">角色</label>
                        <select id="role" name="role" class="form-control" required>
                            <option value="">请选择角色</option>
                            <option value="ADMIN">超级管理员</option>
                            <option value="LAB_MANAGER">实验室管理员</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="collegeId">所属学院</label>
                        <select id="collegeId" name="collegeId" class="form-control">
                            <option value="">请选择学院</option>
                            <option th:each="college : ${colleges}" th:value="${college.id}" th:text="${college.name}">学院</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="contactInfo">联系方式</label>
                        <input type="text" id="contactInfo" name="contactInfo" class="form-control" placeholder="请输入联系方式">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal('addUserModal')">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveUser()">保存</button>
            </div>
        </div>
    </div>

    <!-- 编辑用户模态框 -->
    <div id="editUserModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>编辑用户</h3>
                <span class="close" onclick="closeModal('editUserModal')">&times;</span>
            </div>
            <div class="modal-body">
                <form id="editUserForm">
                    <input type="hidden" id="editUserId" name="id">
                    <div class="form-group">
                        <label for="editUsername">用户名</label>
                        <input type="text" id="editUsername" name="username" class="form-control" required readonly>
                    </div>
                    <div class="form-group">
                        <label for="editName">姓名</label>
                        <input type="text" id="editName" name="name" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label for="editRole">角色</label>
                        <select id="editRole" name="role" class="form-control" required>
                            <option value="ADMIN">超级管理员</option>
                            <option value="LAB_MANAGER">实验室管理员</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="editCollegeId">所属学院</label>
                        <select id="editCollegeId" name="collegeId" class="form-control">
                            <option value="">请选择学院</option>
                            <option th:each="college : ${colleges}" th:value="${college.id}" th:text="${college.name}">学院</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="editContactInfo">联系方式</label>
                        <input type="text" id="editContactInfo" name="contactInfo" class="form-control">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal('editUserModal')">取消</button>
                <button type="button" class="btn btn-primary" onclick="updateUser()">保存</button>
            </div>
        </div>
    </div>

    <script th:src="@{/js/app.js}"></script>
    <script>
        // 当前用户ID（从服务器传递）
        const currentUserId = /*[[${currentUser.id}]]*/ 0;
        
        // 显示添加用户模态框
        function showAddUserModal() {
            document.getElementById('addUserModal').style.display = 'block';
            document.getElementById('addUserForm').reset();
        }

        // 编辑用户
        function editUser(id) {
            // 检查是否试图编辑自己
            if (id == currentUserId) {
                showMessage('不能编辑自己的信息！', 'warning');
                return;
            }
            
            fetch('/api/users/' + id)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // 填充表单数据
                        document.getElementById('editUserId').value = data.id;
                        document.getElementById('editUsername').value = data.username;
                        document.getElementById('editName').value = data.name;
                        document.getElementById('editRole').value = data.role;
                        document.getElementById('editCollegeId').value = data.college ? data.college.id : '';
                        document.getElementById('editContactInfo').value = data.contactInfo || '';
                        
                        // 显示模态框
                        document.getElementById('editUserModal').style.display = 'block';
                    } else {
                        showMessage('获取用户信息失败：' + data.message, 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage('获取用户信息失败，请稍后重试', 'error');
                });
        }

        // 从按钮编辑用户
        function editUserFromButton(button) {
            const id = button.getAttribute('data-id');
            editUser(id);
        }

        // 保存用户
        function saveUser() {
            const form = document.getElementById('addUserForm');
            const formData = new FormData(form);
            
            fetch('/api/users', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    closeModal('addUserModal');
                    showMessage('用户添加成功！', 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showMessage('添加失败：' + data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('添加失败，请稍后重试', 'error');
            });
        }

        // 更新用户
        function updateUser() {
            const form = document.getElementById('editUserForm');
            const formData = new FormData(form);
            const id = document.getElementById('editUserId').value;
            
            // 再次检查是否试图编辑自己
            if (id == currentUserId) {
                showMessage('不能编辑自己的信息！', 'warning');
                return;
            }
            
            fetch('/api/users/' + id, {
                method: 'PUT',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    closeModal('editUserModal');
                    showMessage('用户信息更新成功！', 'success');
                    setTimeout(() => location.reload(), 1000);
                } else {
                    showMessage('更新失败：' + data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showMessage('更新失败，请稍后重试', 'error');
            });
        }

        // 重置密码
        function resetPassword(id) {
            // 检查是否试图重置自己的密码
            if (id == currentUserId) {
                showMessage('不能重置自己的密码！如需修改密码，请联系其他管理员。', 'warning');
                return;
            }
            
            if (confirm('确定要重置该用户的密码吗？密码将重置为默认密码 123456')) {
                fetch('/api/users/' + id + '/reset-password', {
                    method: 'POST'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showMessage('密码重置成功，新密码为：123456', 'success');
                    } else {
                        showMessage('重置失败：' + data.message, 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage('重置失败，请稍后重试', 'error');
                });
            }
        }

        // 从按钮重置密码
        function resetPasswordFromButton(button) {
            const id = button.getAttribute('data-id');
            resetPassword(id);
        }

        // 删除用户
        function deleteUser(id) {
            // 检查是否试图删除自己
            if (id == currentUserId) {
                showMessage('不能删除自己的账户！', 'warning');
                return;
            }
            
            if (confirm('确定要删除这个用户吗？删除后将无法恢复！')) {
                fetch('/api/users/' + id, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showMessage('用户删除成功！', 'success');
                        setTimeout(() => location.reload(), 1000);
                    } else {
                        showMessage('删除失败：' + data.message, 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showMessage('删除失败，请稍后重试', 'error');
                });
            }
        }

        // 从按钮删除用户
        function deleteUserFromButton(button) {
            const id = button.getAttribute('data-id');
            deleteUser(id);
        }

        // 搜索过滤
        function filterUsers() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const table = document.getElementById('userTable');
            const rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
            
            for (let i = 0; i < rows.length; i++) {
                const username = rows[i].getElementsByTagName('td')[1].textContent.toLowerCase();
                const name = rows[i].getElementsByTagName('td')[2].textContent.toLowerCase();
                if (username.includes(searchTerm) || name.includes(searchTerm)) {
                    rows[i].style.display = '';
                } else {
                    rows[i].style.display = 'none';
                }
            }
        }

        // 关闭模态框
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modals = document.getElementsByClassName('modal');
            for (let i = 0; i < modals.length; i++) {
                if (event.target == modals[i]) {
                    modals[i].style.display = 'none';
                }
            }
        }
        
        // Element UI 风格消息提示
        function showMessage(message, type = 'info') {
            const colors = {
                success: '#67C23A',
                error: '#F56C6C',
                warning: '#E6A23C',
                info: '#409EFF'
            };
            
            const messageEl = document.createElement('div');
            messageEl.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: white;
                color: ${colors[type]};
                padding: 15px 20px;
                border: 1px solid ${colors[type]};
                border-radius: 4px;
                box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
                z-index: 9999;
                font-size: 14px;
                max-width: 300px;
                transform: translateX(100%);
                transition: transform 0.3s ease;
            `;
            messageEl.innerHTML = `
                <div style="display: flex; align-items: center; gap: 8px;">
                    <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'times-circle' : type === 'warning' ? 'exclamation-triangle' : 'info-circle'}"></i>
                    <span>${message}</span>
                    <i class="fas fa-times" style="margin-left: auto; cursor: pointer; opacity: 0.6;" onclick="this.closest('div').parentElement.remove()"></i>
                </div>
            `;
            
            document.body.appendChild(messageEl);
            
            // 滑入动画
            setTimeout(() => {
                messageEl.style.transform = 'translateX(0)';
            }, 10);
            
            // 4秒后自动消失
            setTimeout(() => {
                if (messageEl.parentNode) {
                    messageEl.style.transform = 'translateX(100%)';
                    setTimeout(() => {
                        if (messageEl.parentNode) {
                            messageEl.remove();
                        }
                    }, 300);
                }
            }, 4000);
        }
    </script>
</body>
</html> 